//
//  QGAdhocUploadController.m
//  车福内测
//
//  Created by heew on 15/12/8.
//  Copyright © 2015年 heew. All rights reserved.
//

#import "QGAdhocUploadController.h"
#import "AFNetworking.h"
#import "SVProgressHUD.h"
#import "GJCFUitils.h"

@interface QGAdhocUploadController () <UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) NSMutableArray *directory; /**<#属性名#> */
@property (strong, nonatomic) NSURL *parentPath; /**父路径 */
@property (strong, nonatomic) NSFileManager *fileMgr; /**文件管理器 */
@property (strong, nonatomic) void (^myProgressBlock)(NSProgress *progress); /**进度闭包  */
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;
@property (strong, nonatomic) NSProgress *uploadProgress; /**上传进度 */
@end

static NSString *identifier = @"cell";
#define kIconW (GJCFSystemScreenWidth - 4 * 10) / 3

@implementation QGAdhocUploadController
- (NSFileManager *)fileMgr {
    if (_fileMgr == nil) {
        _fileMgr = [NSFileManager defaultManager];
    }
    return _fileMgr;
}
- (NSMutableArray *)directory {
    if (_directory == nil) {
        _directory = [NSMutableArray array];
    }
    return _directory;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    NSString *path = @"/Users";
    NSURL *url = [NSURL URLWithString:path];
    [self updateTableViewWithUrl:url];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"向上" style:UIBarButtonItemStylePlain target:self action:@selector(lastPage)];
    [self.navigationItem.leftBarButtonItem setTintColor:[UIColor whiteColor]];
    self.tabBarItem.title = @"上传";
    self.navigationItem.title = @"手动上传App到蒲公英";
    self.tabBarItem.image = [UIImage imageNamed:@"upload"];

    [self.collectionView registerClass:[QGAdhocUploadCell class] forCellWithReuseIdentifier:identifier];
    self.flowLayout.itemSize = CGSizeMake(kIconW, kIconW + 20);
    self.flowLayout.minimumInteritemSpacing = 10;
    self.flowLayout.minimumLineSpacing = 10;

}


- (void)lastPage {
    NSURL *lastUrl = self.parentPath.URLByDeletingLastPathComponent;
    [self updateTableViewWithUrl:lastUrl];
}

#pragma mark - collectionView datasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.directory.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    QGAdhocUploadCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    NSURL *url = _directory[indexPath.row];
    NSString *string = [url.lastPathComponent stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict = [self.fileMgr attributesOfItemAtPath:url.path error:nil];
    if ([[dict fileType] isEqualToString:NSFileTypeDirectory]) {
        cell.iconView.image = [UIImage imageNamed:@"Folder"];
    }else if ([[dict fileType] isEqualToString:NSFileTypeRegular]){
        NSRange range = [string rangeOfString:@"."];
        if (range.length > 0) {
            NSString *fileString = [string substringFromIndex:range.location + 1];
            if ([fileString isEqualToString:@"ipa"]) {
                cell.iconView.image = [UIImage imageNamed:@"iTunes_ipa_blue"];
            }else{
                cell.iconView.image = [UIImage imageNamed:@"Google_Docs"];
            }
        }
    }
    
    if ([url.pathExtension isEqualToString:@"ipa"]) {
        cell.progressView.observedProgress = self.uploadProgress;
        cell.progressView.hidden = NO;
    }else {
        cell.progressView.observedProgress = nil;
        cell.progressView.hidden = YES;
    }
    cell.textLabel.text = string;
    NSDictionary *textAttr = @{NSFontAttributeName : cell.textLabel.font};
    CGRect rect = [string boundingRectWithSize:CGSizeMake(kIconW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:textAttr context:nil];
    cell.textLabel.gjcf_height = rect.size.height;
    return cell;

}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
        NSURL *url = _directory[indexPath.row];
        if ([url.pathExtension isEqualToString:@"ipa"]) {
            QGAdhocUploadCell *cell = (QGAdhocUploadCell *)[collectionView cellForItemAtIndexPath:indexPath];
            cell.progressView.hidden = NO;
            [self uploadFileWithUrl:url andProgress:^(NSProgress *progress) {
                cell.progressView.observedProgress = progress;
            }];
        }else {
            [self updateTableViewWithUrl:url];
        }
}
//#pragma mark - tableView datasource
//// 组数
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
//    return 1;
//}
//
//// 每一组的行数
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//{
//    return _directory.count;
//}
//
//// 每一个行的细节
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    static NSString *identifier = @"collectionViewcell";
//    NSURL *url = _directory[indexPath.row];
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
//    if (cell == nil) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
//        UIProgressView *progressView = [[UIProgressView alloc] init];
//        progressView.tag = 100;
//        progressView.hidden = YES;
//        [cell.contentView addSubview:progressView];
//        CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
//        progressView.progressTintColor = [UIColor orangeColor];
//        progressView.trackTintColor = [UIColor blueColor];
//        progressView.frame = CGRectMake(16, 40, screenW - 20, 8);
//    }
//    NSString *string = [url.lastPathComponent stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSDictionary *dict = [self.fileMgr attributesOfItemAtPath:url.path error:nil];
//    UIProgressView *progressView = (UIProgressView *)[cell viewWithTag:100];
//    progressView.hidden = NO;
//    if ([dict[@"NSFileType"] isEqualToString:@"NSFileTypeDirectory"]) {
//        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//    }else {
//        cell.accessoryType = UITableViewCellAccessoryNone;
//    }
//    
//    if ([url.pathExtension isEqualToString:@"ipa"]) {
//        progressView.observedProgress = self.uploadProgress;
//        progressView.hidden = NO;
//    }else {
//        progressView.observedProgress = nil;
//        progressView.hidden = YES;
//    }
//    cell.textLabel.text = [NSString stringWithFormat:@"%@",string];
//    return cell;
//}
//
//#pragma mark - tableView delegate
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    NSURL *url = _directory[indexPath.row];
//    if ([url.pathExtension isEqualToString:@"ipa"]) {
//        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//        UIProgressView *progressView = (UIProgressView *)[cell viewWithTag:100];
//        progressView.hidden = NO;
//        [self uploadFileWithUrl:url andProgress:^(NSProgress *progress) {
//            progressView.observedProgress = progress;
//        }];
//    }else {
//        [self updateTableViewWithUrl:url];
//    }
//}
//
- (void)updateTableViewWithUrl:(NSURL *)url {
    NSArray *array = [self.fileMgr contentsOfDirectoryAtURL:url includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
    [self.directory removeAllObjects];
    [self.directory addObjectsFromArray:array];
    [self.collectionView reloadData];
    self.parentPath = url;
}

- (void)uploadFileWithUrl:(NSURL *)url andProgress:(void (^)(NSProgress *progress))progressBlock
{
    NSDictionary *param = @{@"uKey" : @"2168f4055437399fdfb0aeb0949cd96b",
                            @"_api_key" : @"2c103d0ef519c00e4a41dd9428e9d81b"};
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://www.pgyer.com/apiv1/app/upload" parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:url name:@"file" error:nil];
    } error:nil];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, NSDictionary *responseObject, NSError *error) {
        if (error) {
            [SVProgressHUD showErrorWithStatus:error.description];
        } else {
            NSDictionary *dict = responseObject[@"data"];
//            appBuildVersion = 2;
//            appCreated = "2015-12-09 07:35:07";
//            appDescription = "";
//            appFileSize = 6013655;
//            appIcon = 482984d0909ca626e38ba424f446dc61;
//            appIdentifier = "com.autozi.O2OGarage";
//            appIsLastest = 1;
//            appKey = 8242d5ffcf5a77acbf6e3d79d8554f67;
//            appName = "\U8f66\U798f\U7ba1\U5bb6\U5546\U5bb6\U7248";
//            appScreenshots = "";
//            appShortcutUrl = zZbL;
//            appType = 1;
//            appUpdateDescription = "";
//            appUpdated = "2015-12-09 07:35:07";
//            appVersion = "1.2.0";
//            appVersionNo = "1.2.0";
//            userKey = 0a4bac562ae258ad921e24ef1ab72087;
            NSString *status = [NSString stringWithFormat:@"上传成功\n%@\n%@\n",dict[@"appName"],dict[@"appCreated"]];
            [SVProgressHUD showInfoWithStatus:status];
        }
    }];
    
//    self.progressView.observedProgress = progress;
    progressBlock ? progressBlock(progress) : nil;
    self.uploadProgress = progress;
    [uploadTask resume];
}


@end

@implementation QGAdhocUploadCell

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        UIProgressView *progressView = [[UIProgressView alloc] init];
        progressView.hidden = YES;
        progressView.progressTintColor = [UIColor orangeColor];
        progressView.trackTintColor = [UIColor blueColor];
        progressView.frame = CGRectMake(0, kIconW, kIconW, 2);
        [self.contentView addSubview:progressView];
        self.progressView = progressView;
        
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.frame = CGRectMake(20, 20, kIconW - 40, kIconW - 40);
        [self.contentView addSubview:imageView];
        self.iconView = imageView;

        UILabel *textLabel = [[UILabel alloc] init];
        textLabel.frame = CGRectMake(0, kIconW - 12, kIconW, 32);
        textLabel.font = [UIFont systemFontOfSize:13];
        textLabel.textColor = [UIColor whiteColor];
        textLabel.numberOfLines = 0;
        textLabel.textAlignment = NSTextAlignmentCenter;
        [self.contentView addSubview:textLabel];
        self.textLabel = textLabel;

    }
    return self;
}

@end
